/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ServerWindows;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JOptionPane;

/**
 *
 * @author Mohamad
 */
public class LoginWindow extends javax.swing.JFrame {

    /**
     * Creates new form LoginWindow
     */
    public LoginWindow() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        usernameLabel = new javax.swing.JLabel();
        passwordLabel = new javax.swing.JLabel();
        usernameTextField = new javax.swing.JTextField();
        passwordPasswordField = new javax.swing.JPasswordField();
        loginJButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Login - JMessanger Server");
        setResizable(false);
        setType(java.awt.Window.Type.POPUP);

        usernameLabel.setText("Username");

        passwordLabel.setText("Password");

        loginJButton.setText("Login");
        loginJButton.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        loginJButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                loginJButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(usernameLabel)
                            .addComponent(passwordLabel))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(usernameTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 195, Short.MAX_VALUE)
                            .addComponent(passwordPasswordField)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(95, 95, 95)
                        .addComponent(loginJButton, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(18, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(102, 102, 102)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(usernameLabel)
                            .addComponent(usernameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(24, 24, 24)
                        .addComponent(passwordPasswordField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(passwordLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 26, Short.MAX_VALUE)
                .addComponent(loginJButton)
                .addGap(56, 56, 56))
        );

        usernameLabel.getAccessibleContext().setAccessibleName("usernameLabel");
        passwordLabel.getAccessibleContext().setAccessibleName("passwordLabel");
        usernameTextField.getAccessibleContext().setAccessibleName("usernameTextField");
        passwordPasswordField.getAccessibleContext().setAccessibleName("passwordPasswordField");
        loginJButton.getAccessibleContext().setAccessibleName("loginJButton");

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void loginJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loginJButtonActionPerformed
        // TODO add your handling code here:
        boolean isUsernameValid = false;
        boolean isPasswordValid = false;

        //Validating the username.
        /*
         * Used regular expression info
         * http://regexlib.com/(A(QcGAqDUMjOPRot1JnUucqjx77s43cDmmH6dupm3g9u6zDgm10pP2yScx25gaxyiY_zpNWvViYgbxZzkqxeVhHuHeJvF-N7Wr-GfRwucopX-Ra4eGK2_-4c-qdawIQtVcIIAOYb2Zz81VzQImRzElLFwsPylkyM_lYik5r8JomOBYm4GWYjapL8v-S3__T39-0))/REDetails.aspx?regexp_id=3048
         * This expression:
         * Matches
         * a.f | joe | mehdi2_ghasemi | mr-green123
         * Non-Matches	
         * a._f | 1mehdi | ab | mehdi..ghasemi | mehdi_
         */
        Pattern pattern = Pattern.compile("[A-Za-z](\\.[A-Za-z0-9]|\\-[A-Za-z0-9]|_[A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9])(\\.[A-Za-z0-9]|\\-[A-Za-z0-9]|_[A-Za-z0-9]|[A-Za-z0-9])*");
        Matcher matcher = pattern.matcher(usernameTextField.getText());
        isUsernameValid = matcher.matches();
        //validating password.
        /**
         * Regular Expression used:
         * http://regexlib.com/(A(QcGAqDUMjOPRot1JnUucqjx77s43cDmmH6dupm3g9u6zDgm10pP2yScx25gaxyiY_zpNWvViYgbxZzkqxeVhHuHeJvF-N7Wr-GfRwucopX-Ra4eGK2_-4c-qdawIQtVcIIAOYb2Zz81VzQImRzElLFwsPylkyM_lYik5r8JomOBYm4GWYjapL8v-S3__T39-0))/REDetails.aspx?regexp_id=515
         * I built this expression to test a string in ASP for valid username
         * and password constraints. It can be adapted for any number of
         * scenerios. For instance in this case, we needed to ensure the
         * username someone wanted was not all numbers or all letters and was
         * 6-15 characters in length with no special characters. This expression
         * tests negatively for all number cases, then all letter cases, and
         * lastly tests for only alphanumeric characters in the required range.
         * In other words: the match must be alphanumeric with at least one
         * number, one letter, and be between 6-15 character in length. Matches
         * C2dfeed | sporttrak1 | 11223a -Matches pookie | d34_fff | 123456
         */
        pattern = Pattern.compile("(?!^[0-9]*$)(?!^[a-zA-Z]*$)^([a-zA-Z0-9]{6,15})$");
       // matcher = pattern.matcher(passwordPasswordField.getPassword().toString());
        matcher = pattern.matcher(new String(passwordPasswordField.getPassword()));
        isPasswordValid = matcher.matches();
        if(isUsernameValid && isPasswordValid) {
         /**
         * On a succesful validation, contacting the server to check login
         * credentials.
         * 
         * BL.LoginServices loginServices = new BL.LoginServices();
         * loginServices.login(usernameTextField.getText(), passwordPasswordField.getText());
         */
        }        
        else {
         /**
         * Logging in or asking to check credentials.
         * we can use a JOption Pane.
         */
         JOptionPane.showMessageDialog(this,"Invalid username or password.", "Login Error", JOptionPane.ERROR_MESSAGE);
          
        }
    }//GEN-LAST:event_loginJButtonActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(LoginWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(LoginWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(LoginWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(LoginWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new LoginWindow().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton loginJButton;
    private javax.swing.JLabel passwordLabel;
    private javax.swing.JPasswordField passwordPasswordField;
    private javax.swing.JLabel usernameLabel;
    private javax.swing.JTextField usernameTextField;
    // End of variables declaration//GEN-END:variables
}
